package com.bw.service.customer.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bw.entity.customer.PiCustomer;
import com.bw.entity.linkman.PiLinkman;
import com.bw.mapper.customer.PiCustomerMapper;
import com.bw.resp.ResponseResult;
import com.bw.service.customer.IPiCustomerService;
import com.bw.service.linkman.IPiLinkmanService;
import com.bw.utils.sms.SendSms;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author fankai
 * @since 2020-06-18
 */
@Service
public class PiCustomerServiceImpl extends ServiceImpl<PiCustomerMapper, PiCustomer> implements IPiCustomerService {

    private final Logger logger = LoggerFactory.getLogger(PiCustomerServiceImpl.class);

    @Autowired
    private IPiLinkmanService linkmanService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public ResponseResult sendCode(String tel) {
        ResponseResult result = ResponseResult.SUCCESS();
        //判断用户是否存在，为空的话提示错误
        QueryWrapper queryWrapper = new QueryWrapper();
        if (tel!=null){
            queryWrapper.eq("tel",tel);
        }
        //获取手机 号码为条件list
        List<PiLinkman> list = linkmanService.list(queryWrapper);
        if (list.size()<=0 || list==null){
            logger.info("用户不存在");
            result.setSuccess(false);
            result.setMessage("用户不存在");
            return result;
        }
        //判断验证码是否频繁（一分钟两次）
        //存入手机号为key之后过期时间为一分钟 如果一分钟之内有这个数据的话则是频繁发送
        Boolean y = redisTemplate.boundValueOps("S" + tel).setIfAbsent("y",1, TimeUnit.MINUTES);
        if (!y){
            logger.info("发送频繁!");
            result.setSuccess(false);
            result.setMessage("发送频繁");
            return result;
        }
        //判断是否达到上限(一天十次)
        String num = redisTemplate.boundValueOps("P"+tel).get();
        if (num!=null){
            if (Integer.valueOf(num)>10){
                result.setSuccess(false);
                result.setMessage("今日的发送达到上线");
                return result;
            }
        }else{
            redisTemplate.boundValueOps("P"+tel).expire(1,TimeUnit.DAYS);
        }
        redisTemplate.boundValueOps("P"+tel).increment();

        //发送验证码
        String yzm = getyzm();
        redisTemplate.boundValueOps("Y"+tel).set(yzm,90,TimeUnit.SECONDS);
        logger.info(yzm);
        //SendSms.SendSms(tel,yzm);
        return result;
    }


    private String getyzm(){
        String yzm = "";
        for (int i=0;i<6;i++){
            yzm+= new Random().nextInt(10);
        }
        return yzm;
    }
}
